package com.simple.gateway.core.datasource.connection.rpc;

import com.simple.gateway.core.datasource.connection.RpcConnection;
import com.simple.gateway.core.mapping.HttpStatement;
import com.simple.gateway.core.session.Configuration;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * 项目: simple-gateway-core
 *
 * 功能描述: dubbo实现
 *
 * @author: WuChengXing
 *
 * @create: 2023-08-04 16:50
 **/
public class DubboConnection extends RpcConnection {

    private final GenericService genericService;

    public DubboConnection(Configuration configuration, HttpStatement httpStatement) {
        // 配置信息
        String application = httpStatement.getApplication();
        String interfaceName = httpStatement.getInterfaceName();
        // 获取服务
        ApplicationConfig applicationConfig = configuration.getApplicationConfig(application);
        RegistryConfig registryConfig = configuration.getRegistryConfig(application);
        ReferenceConfig<GenericService> reference = configuration.getReferenceConfig(interfaceName);
        // 连接远程服务
        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        bootstrap.application(applicationConfig).registry(registryConfig).reference(reference).start();
        // 获取泛化接口
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        genericService = cache.get(reference);
    }

    /**
     * Dubbo 泛化调用：https://dubbo.apache.org/zh/docsv2.7/user/examples/generic-reference/
     */
    @Override
    public Object execute(String method, String[] parameterTypes, String[] parameterNames, Object[] args) {
        return genericService.$invoke(method, parameterTypes, args);
    }
}
